<template>
	<u-sticky bgColor="#F5F6F8">
		<view class="tabs">
			<u-tabs itemStyle="height: 100rpx;font-size: 30rpx;'" lineColor="#5780EF"
				activeStyle="color: #5780EF;" inactiveStyle="color: #606672;" :current="current" :list="tabsList"
				@click="tabsChange"></u-tabs>
		</view>
	</u-sticky>

	<view class="order-list">
		<view class="order-item" v-for="(item, i) in orderList" :key="i" @tap="goOrderDetail(item)">
			<view class="status-box">
				<view class="name">{{ systemStore.mallName ?? '' }}</view>
				<!-- 状态判断 -->
				<view class="status" v-if=" item.status === 'unpaid' ">
					<text>待支付：</text>
					<view class="">
                        <uni-countdown :font-size="14" color="#f55726" :show-day="false"
                                       :hour="item.remainingTime.hours"
                                       :minute="item.remainingTime.minutes"
                                       :second="item.remainingTime.seconds" />
					</view>
				</view>
				<view class="status" v-else-if=" item.status === 'paid' ">待发货</view>
				<view class="status" v-else-if=" item.status === 'shipped' ">待收货</view>
                <view class="status1" v-else-if=" item.status === 'completed' ">已完成</view>
                <view class="status1" v-else-if=" item.status === 'cancelled' ">已取消</view>


                <!-- 售后中状态判断 -->
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'refunding' ">退款中</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'refunded' ">已退款</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'refund_fail' ">退款失败</view>

				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'returning_refunding' ">退货退款中</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'return_refund_agree' ">待寄回</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'return_refund_back' ">已寄回</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'return_refunded' ">已退货退款</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'return_refund_fail' ">退货退款失败</view>

				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'exchanging' ">换货中</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'exchange_agree' ">待寄回</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'exchange_back' ">已寄回</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'exchange_fail' ">换货失败</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'exchange_shipped' ">换货已发货</view>
				<view class="status" v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'exchange' ">换货完成</view>

			</view>
			<view class="content-box" v-for="(product, key) in item.order_products" :key="key">
				<view class="icon">
					<u-image width="180rpx" height="180rpx" :src="getServerStatic('/static/images/a21.png')"></u-image>
				</view>
				<view class="left">
					<u-image width="170rpx" height="155rpx" :src="checkAndFixUrl(product.product_cover)" mode="aspectFit"></u-image>
				</view>
				<view class="right">
					<view class="com-title">{{ product.product_name }}</view>
					<view class="sku-box">规格：{{ product.product_sku }}</view>
					<view class="count-box">购买数量：{{ product.quantity }}件</view>
				</view>
			</view>
			<view class="btns-box">
				<!-- 待支付按钮 -->
				<template v-if=" item.status === 'unpaid' ">
					<view>
						<u-button plain throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="true" type="mini" shape="circle" color="#5780EF"
                                  @tap.stop="showCancelPop(item)">取消订单</u-button>
					</view>
					<view>
						<u-button throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="false" type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                                  @tap.stop="actionPay(item)">去支付</u-button>
					</view>
				</template>
				<!-- 待发货 -->
				<template v-else-if=" item.status === 'paid' ">
					<view>
						<u-button plain throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="true" type="mini"
                                  shape="circle" color="#5780EF" @tap.stop="showCancelPop(item)">取消订单</u-button>
					</view>
					<view>
						<u-button throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="false" type="mini" shape="circle"
                                  color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)" @tap.stop="showMallMobile = true">联系客服</u-button>
					</view>
				</template>
				<!-- 待收货 -->
				<template v-else-if=" item.status === 'shipped' ">
					<view>
						<u-button plain throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="true" type="mini" shape="circle"
                                  color="#5780EF" @tap.stop="showMallMobile = true">联系客服</u-button>
					</view>
					<view>
						<u-button throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="false" type="mini" shape="circle"
                                  color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)" @tap.stop="handleConfirmReceipt(item)">确认收货</u-button>
					</view>
				</template>
				<!-- 退款已完成 已完成 -->
				<template v-else-if=" item.status === 'completed' ">
					<view>
						<u-button throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="false" type="mini" shape="circle"
                                  color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)" @tap.stop="handlePurchaseAgain">再次购买</u-button>
					</view>
				</template>

				<!-- 售后中状态判断 -->
				<!-- 申请退款中 -->
				<template v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'refunding' ">
					<view>
						<u-button plain throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="true" type="mini" shape="circle" color="#5780EF" @tap.stop="showMallMobile = true">联系客服</u-button>
					</view>
<!--					<view>-->
<!--						<u-button throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="false" type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)">取消退款</u-button>-->
<!--					</view>-->

                    <view>
                            <u-button throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="false" type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)" @tap.stop="handleCheckRma(item)">查看售后</u-button>
                    </view>

				</template>
				<!-- 退货退款中 换货中 -->
				<template v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'exchanging' ">
					<view>
						<u-button plain throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="true" type="mini" shape="circle" color="#5780EF" @tap.stop="showMallMobile = true">联系客服</u-button>
					</view>
					<view>
						<u-button throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="false" type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)" @tap.stop="handleCheckRma(item)">查看售后</u-button>
					</view>
				</template>
				<!-- 换货已发货 -->
				<template v-else-if=" item.status === 'after_sale' && item.after_sale_status === 'exchange_shipped' ">
					<view>
						<u-button plain throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="true" type="mini" shape="circle" color="#5780EF" @tap.stop="showMallMobile = true">联系客服</u-button>
					</view>
					<view>
						<u-button throttleTime="1000" :customStyle="{width: '170rpx', height: '56rpx'}" :hairline="false" type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)" @tap.stop="handleConfirmReceipt(item)">确认收货</u-button>
					</view>
				</template>
			</view>
		</view>

        <u-loadmore :status="loadMoreStatus" />
	</view>

    <!-- 取消订单弹窗 -->
    <u-popup closeable bgColor="transparent" :show="cancelPop" @close="cancelPop = false">
        <view class="cancel-pop">
            <view class="pop-title">请选择取消订单的原因（必选）：</view>
            <view class="radio-wrap">
                <u-radio-group v-model="radioValue" placement="column">
                    <u-radio  :customStyle="{marginBottom: '46rpx'}" v-for="(item, index) in radioList" :key="index" activeColor="#6087EF"
                              :label="item.name" :name="item.name">
                    </u-radio>
                </u-radio-group>
            </view>
            <view class=" ">
                <u-button throttleTime="1000" :customStyle="{height: '86rpx', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)', letterSpacing: '.1rem'}"
                          :hairline="false"
                          type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                          @tap="toCancel"
                >确认</u-button>
            </view>
        </view>
    </u-popup>

    <!-- 客服电话 -->
    <u-action-sheet round="30rpx" :show="showMallMobile" :actions="mallMobileActions" title="" description="" @close="showMallMobile = false"
                    @select="callMallMobileConfirm">
    </u-action-sheet>

</template>

<script setup>
    import {ref, reactive, readonly} from "vue"
    import {onLoad, onShow, onPullDownRefresh , onReachBottom} from '@dcloudio/uni-app'
    import useUniAPi from "@/hooks/useUniAPi";
    import {useSystemStore, useUserStore} from "@/store";
    import {cancellationMallOrder, confirmMallDelivery, getMallOrderList} from "@/api/mall";
    import {checkAndFixUrl, getServerStatic} from "@/utils/tool";
    const { navigateTo, redirectTo, goBack, payment } = useUniAPi()

    // 用户store
    const userStore = useUserStore();
    // 系统
    const systemStore = useSystemStore()

    const loadMoreStatus = ref('loadmore')
    const currentPage = ref(1)
    const perPage = ref(10)

    onLoad((evt) => {
        console.log('商城订单列表', evt)
    })

    onShow(() => {
        refreshPage()
        handleGetOrderList()
    })

	const current = ref(0)
	const tabsList = ref([
        {
			name: '全部',
            type: 'all'
		},
		{
			name: '待支付',
            type: 'unpaid'
		},
		{
			name: '待发货',
            type: 'paid'
		},
		{
			name: '待收货',
            type: 'shipped'
		},
		{
			name: '售后中',
            type: 'after_sale'
		},
		{
			name: '已完成',
            type: 'completed'
		}
	])

	// 订单列表
	const orderList = ref([])
    const status = ref('all')
    // 获取参数.
    const getSearchParams = () => {
        return {
            status: status.value,
            currentPage: currentPage.value,
            perPage: perPage.value,
        }
    }

    const handleGetOrderList = async () => {
        let param = getSearchParams()
        loadMoreStatus.value = 'loading'

        const {code, data} = await getMallOrderList(param)
        if (code === 1) {
            if (data.length <= 0) {
                loadMoreStatus.value = 'nomore'
                console.log('noting')
            } else {
                currentPage.value++
                // 数量少于每页数量
                if (data.length < perPage.value) {
                    loadMoreStatus.value = 'nomore'
                } else {
                    loadMoreStatus.value = 'loadmore'
                }
            }

            let list = data.map(item => {
                // 克隆对象
                const clonedItem = { ...item };

                // 计算剩余时间
                const endTime = new Date(item.payment_end_time).getTime();
                const currentTime = new Date().getTime();
                const timeDifference = Math.max(0, endTime - currentTime); // 确保剩余时间不为负数

                const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
                const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
                const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

                // 将计算得到的时分秒添加到克隆的对象中
                clonedItem.remainingTime = {
                    // hours: hours < 10 ? '0' + hours : hours,
                    // minutes: minutes < 10 ? '0' + minutes : minutes,
                    // seconds: seconds < 10 ? '0' + seconds : seconds
                    hours: hours < 10 ?  hours : hours,
                    minutes: minutes < 10 ? minutes : minutes,
                    seconds: seconds < 10 ? seconds : seconds
                };

                return clonedItem;
            })

            orderList.value = orderList.value.concat(list)
        } else {
            loadMoreStatus.value = 'nomore'
        }
    }

	const tabsChange = (e) => {
		current.value = e.index
        status.value = e.type
        refreshPage()
        handleGetOrderList()
	}

    onReachBottom(() => {
        handleGetOrderList()
        console.log("上拉加载更多")
    })


    // 刷新数据.
    const refreshPage = () => {
        currentPage.value = 1
        orderList.value = []
    }

	const goOrderDetail = (item) => {
		uni.navigateTo({
			url: `/mine/commodity/detail?order_id=${item.id}`
		})
	}

    const actionPay = (item) => {
        uni.navigateTo({
            url: `/mine/commodity/detail?order_id=${item.id}`
        })
    }


    const cancelPop = ref(false)
    const cancelOrderId = ref(0)
    // 单选
    const radioValue = ref('')
    const radioList = ref([{
        name: '不想要了',
    },
        {
            name: '选错/多选',
        },
        {
            name: '收件人人填错了',
        },
        {
            name: '商品选错了',
        },
        {
            name: '有更便宜的了，不想要了/其他原因',
        },
    ])

    const showCancelPop = (item) => {
        console.log('取消',item.id)
        cancelOrderId.value = item.id
        cancelPop.value = true
    }

    // 取消订单.
    const toCancel = async () => {
        console.log(radioValue.value)
        if (!radioValue.value) {
            uni.showToast({
                mask: true,
                title: '请选择原因!',
                icon: 'error'
            })
            return
        }

        cancelPop.value = false
        uni.showLoading({
            title: '加载中'
        });
        const {code, data, message} = await cancellationMallOrder({orderId: cancelOrderId.value, cancelReason: radioValue.value})
        uni.hideLoading();

        if (code == 1) {
            uni.showToast({
                mask: true,
                title: '取消完成',
                icon: 'success'
            })
            userStore.syncUserInfo()
            refreshPage()
            handleGetOrderList()
        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                }
            });
        }
    }

    const handleCheckRma = (item) => {
        uni.navigateTo({
            url: `/mine/commodity/after-sales-detail?order_id=${item.id}&order_status=${item.status}&after_sale_status=${item.after_sale_status}`
        })
    }

    // 确认收货
    const handleConfirmReceipt = (item) => {
        console.log('确认收货', item.id)
        uni.showModal({
            title: '提示',
            content: "确认收货?",
            showCancel: true,
            success: function (res) {
                if (res.confirm) {
                    const toReceipt = async () => {
                        uni.showLoading({
                            title: '加载中'
                        });
                        const {code, data, message} = await confirmMallDelivery({orderId: item.id})
                        uni.hideLoading();

                        if (code === 1) {
                            await handleGetOrderInfo()
                        } else {
                            uni.showModal({
                                title: '提示',
                                content: message ?? "请求异常",
                                showCancel: false,
                                success: function (res) {
                                }
                            });
                        }
                    }
                    toReceipt()
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
            }
        });
    }

    // 点击再次购买
    const handlePurchaseAgain = () => {
        redirectTo({
            url: "/pages/home/home"
        })
    }

    // 客服
    const showMallMobile = ref(false)
    const mallMobileActions = ref([{
        name: `一键拨打：${systemStore.mallCustomerMobile}`,
        isCall: true
    },
        {
            name: '取消',
            isCall: false
        },
    ])

    const callMallMobileConfirm = (e) => {
        if (e.isCall) {
            uni.makePhoneCall({
                phoneNumber: systemStore.mallCustomerMobile
            })
        }
    }
</script>

<style lang="scss" scoped>
    .empty-box {
        @include center(100%, 100vh);
    }

    .cancel-pop {
        padding: 40rpx;
        background: #FFFFFF;
        box-shadow: 0rpx 0rpx 30rpx 1rpx rgba(153, 153, 153, 0.16);
        border-radius: 30rpx 30rpx 0rpx 0rpx;

        .pop-title {
            color: #000000;
            font-size: 32rpx;
            font-weight: bold;
        }

        .info {
            margin-top: 14rpx;
            margin-bottom: 40rpx;
            background: #F6F6F6;
            border-radius: 20rpx;
            padding: 26rpx 30rpx;
            color: #000000;

            &>view {
                margin-bottom: 16rpx;
            }
        }
        .radio-wrap {
            margin-top: 36rpx;
        }
        .cancel-btn {
            // box-shadow: 0rpx 0rpx 16rpx 1rpx rgba(0,0,0,0.1);
            margin-top: 50rpx;
        }
    }

	.order-list {
		margin-top: 40rpx;
		padding: 0 26rpx 150rpx;
		.order-item {
			padding: 36rpx 30rpx;
			background: #FFFFFF;
			border-radius: 30rpx;
			margin-bottom: 26rpx;
            box-shadow: 0 0 20rpx 1rpx rgba(187,187,187,.16);

			.status-box {
				@include between(100%);
				padding-bottom: 30rpx;
				border-bottom : 1rpx solid #E8E8E8;
				margin-bottom: 30rpx;
				.name {
					color: #312C2A;
				}
				.status {
					display: flex;
					align-items: center;
					color: #6087EF;
				}
				.status1 {
					color: #AAAAAA;
				}
			}
			.content-box {
				@include between(100%, 100%);
				position: relative;
				.right {
					flex: 1;
					margin-left: 22rpx;
					@include between(100%, 170rpx);
					flex-direction: column;
					align-items: flex-start;
					padding: 10rpx 0;
					color: #000000;
					font-size: 30rpx;
					.com-title {
						@include over-ellip(450rpx);
						font-weight: bold;
					}
                    .sku-box {
                        @include over-ellip(450rpx);
                    }
				}
				.icon {
					position: absolute;
					bottom: 0;
					right: 0;
					z-index: 99;
				}
			}
			.btns-box {
				padding-top: 32rpx;
				border-top: 1rpx solid #E8E8E8;
				margin-top: 30rpx;
				@include end(100%);
				& > view {
					margin-left: 24rpx;
				}
				.message {
					font-size: 26rpx;
					color: #D66A44;
				}
			}
		}
	}
</style>
